package com.kuding.aop;

import com.kuding.anno.ExceptionListener;
import com.kuding.exceptionhandle.ExceptionHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

import java.util.Arrays;
import java.util.Objects;

@Aspect
public class ExceptionNoticeAop {

    private ExceptionHandler exceptionHandler;

    private final Log logger = LogFactory.getLog(getClass());

    public ExceptionNoticeAop(ExceptionHandler exceptionHandler) {
        this.exceptionHandler = exceptionHandler;
    }

    @AfterThrowing(value = "@within(listener)", throwing = "e", argNames = "listener,e")
    public void exceptionNotice(JoinPoint joinPoint, ExceptionListener listener, RuntimeException e) {
        handleException(e, joinPoint.getSignature().getName(), joinPoint.getArgs());
    }

    @AfterThrowing(value = "@annotation(listener)", throwing = "e", argNames = "listener,e")
    public void exceptionNoticeWithMethod(JoinPoint joinPoint, ExceptionListener listener, RuntimeException e) {
        handleException(e, joinPoint.getSignature().getName(), joinPoint.getArgs());
    }

    private void handleException(RuntimeException exception, String methodName, Object[] args) {
        if (args != null && args.length != 0) {
            String[] strings = Arrays.stream(args).filter(Objects::nonNull).map(Object::toString).toArray(String[]::new);
            logger.debug("出现异常：" + methodName + String.join(",", strings));
        }
        exceptionHandler.createNotice(exception, methodName, args);
    }
}
